<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IndexedDB练习</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"
        integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-7ymO4nGrkm372HoSbq1OY2DP4pEZnMiA+E0F3zPr+JQQtQ82gQ1HPY3QIVtztVua"
        crossorigin="anonymous"></script>
    <style>
        #app {
            width: 80%;
            margin: 20px auto;
        }

        .form {
            position: absolute;
            left: 50%;
            top:50%;
            transform: translate(-50%,-50%);
            width: 40vw;
            margin: 30px auto;
            padding: 30px;
            box-sizing: border-box;
            background: #F0F0F0;
            box-shadow: 1px 2px 8px rgba(150, 150, 150, .6);
            border-radius: 7px;
        }
    </style>
</head>

<body>
    <div id="app">
        <div class="form" v-show="addShow">
            <div class="alert alert-warning" v-show="showWarnning" role="alert">
                {{warning}}
                <button type="button" class="close" @click="showWarnning=false">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="alert alert-success" v-show="showSuccess" role="alert">
                {{success}}
                <button type="button" class="close" @click="showSuccess=false">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="form-group row">
                <label for="name" class="col-sm-2 col-form-label">用户名</label>
                <input placeholder="输入用户名" id="name" class="form-control col-sm-10" v-model="addForm.name" />
            </div>
            <div class="form-group row">
                <label class="col-sm-2 col-form-label">年龄</label>
                <input placeholder="输入年龄" type="number" class="form-control col-sm-10" v-model="addForm.age" />
            </div>
            <div class="form-group row">
                <label class="col-sm-2 col-form-label" for="exampleFormControlFile1">选择头像</label>
                <input type="file" class="form-control-file col-sm-10" id="exampleFormControlFile1">
            </div>
            <div class="form-group row">
                <label class="col-sm-2 col-form-label">性别</label>
                <select class="form-control col-sm-10" placeholder="选择性别" v-model="addForm.gender">
                    <option value="">选择性别</option>
                    <option value="1">男</option>
                    <option value="2">女</option>
                </select>
            </div>
            <div class="form-group row">
                <div class="col-sm-2"></div>
                <div class="col-sm-10">
                    <button class="btn btn-primary" @click="addUser">添加用户</button>
                    <button class="btn btn-info" @click="addShow=false">取消</button>
                </div>
            </div>
        </div>

        <div class="tool-bar">
            <button class="btn btn-sm btn-primary" @click="addShow=true">添加用户</button>
        </div>

        <table class="table table-bordered" style="margin: 10px auto;">
            <thead class="thead-light">
                <tr>
                    <th>ID</th>
                    <th>姓名</th>
                    <th>头像</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(item,index) in userList" ::key="index">
                    <th>{{item.id}}</th>
                    <th>{{item.name}}</th>
                    <th></th>
                    <th>{{item.age}}</th>
                    <th>{{item.gender ==1 ? "男" : "女"}}</th>
                    <th>
                        <button class="btn btn-primary btn-sm">编辑</button>
                        <button class="btn btn-danger btn-sm" @click="deleteDB(item.id)">删除</button>
                    </th>
                </tr>
            </tbody>
        </table>
    </div>

    <script>
        
        let vm = new Vue({
            el: "#app",
            data: {
                
                db: null,//db对象
                db_name: "liguanh_Db", //数据库字段
                table_name: "users",//数据表的字段
                version: 1,//版本
                addShow:false,
                addForm: {
                    name: "",
                    age: "",
                    headPic: "",
                    gender: "",
                },
                showWarnning: false,
                warning: "请输入表单内容",
                showSuccess: false,
                success: "",
                userList: [],
            },
            async created() {
                await this.connectDB();

                this.getAllList();
            },
            mounted() {
                
            },
            methods: {
                //使用indexDB完成增删改查的代码
                deleteDB(id) {
                    //开启事物的风法封装
                    let store = this.db.transaction([this.table_name], "readwrite").objectStore(this.table_name);

                    return new Promise((resolve, reject) => {
                        let req = store.delete(id);//通过id执行删除

                        req.addEventListener("error", () => {
                            console.log("删除失败");
                            reject("删除失败");
                        })

                        req.addEventListener("success", () => {
                            console.log("删除成功");
                            resolve("成功");
                            this.getAllList();
                        })
                    })
                },
                getAllList() {
                    return new Promise((resolve, reject) => {
                        //开启事物的风法封装
                        let store = this.db.transaction([this.table_name], "readwrite").objectStore(this.table_name);
                        let request = store.getAll();

                        request.addEventListener("error", () => {
                            console.log("查询列表失败")
                            reject("查询失败");
                        })

                        request.addEventListener("success", (event) => {
                            console.log("查询数据成功");
                            this.userList = event.target.result.reverse();
                            resolve(event.target.result);
                        })
                    })
                },
                //首先链接indexDB数据库信息操作
                connectDB() {
                    return new Promise((resove, reject) => {
                        //第一步打开数据建库的链接操作
                        requestDB = window.indexedDB.open(this.db_name, this.version);
                        //监听成功或者失败的方法
                        requestDB.addEventListener("error", () => {
                            console.error("The programe is not allowed connect to indexedDB,please try again!")
                            reject();
                        })

                        requestDB.addEventListener("success", (event) => {
                            console.log("链接数据库成功")
                            this.db = event.target.result;//把链接数据库对象返回的结果对象赋值给db对象

                            // this.getList();
                            resove(this.db);//使用Promise封装对象
                        })

                        //版本链接的更新的操作,一般的指出发一次
                        requestDB.addEventListener("upgradeneeded", event => {
                            console.log("更新数据库源操作对象，一般是第一次链接的触发")
                            this.db = event.target.result;//获取数据库源操作对象

                            this.db.addEventListener("error", event => {
                                console.log("连接数据库集合失败");
                            })

                            //判断集合是否存在？，创建集合和索引的信息
                            if (!this.db.objectStoreNames.contains(this.table_name)) {
                                //创建一个对象存储
                                stores = this.db.createObjectStore(this.table_name, { keyPath: "id", autoIncrement: true })
                            }

                            //创建一个唯一的索引值，字段名，索引名字，是否唯一其他属性
                            stores.createIndex("name", "name", { unique: true });
                        })
                    })
                },

                //添加用户的操作
                addUser() {
                    //最基本的表单校验逻辑处理
                    let { name, age, gender } = this.addForm;
                    if (name == "" || age == "" || gender == "") {
                        this.showWarnning = true;
                        setTimeout(() => {
                            //关闭提示信息
                            this.showWarnning = false;
                        }, 3500)
                        return false;
                    }

                    //开启事物的风法封装
                    let store = this.db.transaction([this.table_name], "readwrite").objectStore(this.table_name);
                    //开始添加数据的内容信息
                    let res = store.add(this.addForm);

                    res.addEventListener("error", (event) => {
                        this.warning = "添加用户失败" + event.target;
                        this.showWarnning = true;
                        setTimeout(() => {
                            //关闭提示信息
                            this.showWarnning = false;
                        }, 3500)
                    })

                    res.addEventListener("success", () => {
                        this.addForm = {
                            name: "",
                            age: "",
                            headPic: "",
                            gender: "",
                        };
                        this.success = "添加用户成功";
                        this.showSuccess = true;
                        setTimeout(() => {
                            //关闭提示信息
                            this.showSuccess = false;
                            this.addShow = false;
                        }, 2500)
                        this.getAllList();
                    })
                }
            },
        })
    </script>
</body>

</html>